package com.frogs.ucenter.v1.service.impl.aop;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.ucenter.v1.util.ApiConstants;

@Aspect
@Service(ApiConstants.VERSION+"apiCostTimeAopImpl")
public class ApiCostTimeAopImpl{
	private static final Logger log = LoggerFactory.getLogger("com.frogs.ucenter.service.impl.aop.ApiCostTimeAopImpl");
	
	@Before("execution(* com.frogs.ucenter.v1.controller..*.*(..) )")
	public void doBefore(JoinPoint jp){
		for(Object object : jp.getArgs()) {
			if (object instanceof HttpServletRequest) {
				HttpServletRequest req = (HttpServletRequest)object;//切入点方法入参
				req.setAttribute("POINT_START_TIME", new Date().getTime());
			}
		}
		
		
	}
	
	@After("execution(* com.frogs.ucenter.v1.controller..*.*(..) )")
	public void doAfter(JoinPoint jp){
		try{
			for(Object object : jp.getArgs()) {
				if (object instanceof HttpServletRequest) {
					String methodName = jp.getSignature().getName();
					String className = jp.getTarget().getClass().getName();
					HttpServletRequest req = (HttpServletRequest)object;//切入点方法入参
					
					long startTime = Long.parseLong(req.getAttribute("POINT_START_TIME").toString());
					long ms = DateUtil.getIntervalMs(new Date(startTime), new Date());
					
					log.info("cost time[{}] {} func[{}] paramsmap[{}] {}",new Object[] { ms+"ms" , className, methodName, 
							JSON.toJSONString(req.getParameterMap()) , DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss")});
					break;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
}
